package com.xiaochangwei.web.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xiaochangwei.web.beans.City;
import com.xiaochangwei.web.beans.Hobby;
import com.xiaochangwei.web.service.BasicDataService;

/**
 * @since 2017年3月9日 下午7:58:21
 * @author 肖昌伟 317409898@qq.com
 * @description
 */
@RestController
public class BasicDataController implements InitializingBean {

	private Map<Long, List<City>> cityCache = new ConcurrentHashMap<Long, List<City>>(500);

	private Map<Long, List<Hobby>> hobbyCache = new ConcurrentHashMap<Long, List<Hobby>>(500);

	@Autowired
	private BasicDataService basicDataService;

	@RequestMapping("/city/{code}")
	public List<City> getCitys(@PathVariable Long code) {
		List<City> result = new ArrayList<>();
		if (cityCache.containsKey(code)) {
			return cityCache.get(code);
		} else {
			result = basicDataService.getCity(code);
			cityCache.put(code, result);
		}
		return result;
	}

	@RequestMapping("/hobby/{code}")
	public List<Hobby> getHobbys(@PathVariable Long code) {
		List<Hobby> result = new ArrayList<>();
		if (hobbyCache.containsKey(code)) {
			return hobbyCache.get(code);
		} else {
			result = basicDataService.getHobby(code);
			hobbyCache.put(code, result);
		}
		return result;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		final Thread clearThread = new Thread(new Runnable() {
			public void run() {
				while (true) {
					try {
						Thread.sleep(60 * 60 * 24 * 1000);
					} catch (InterruptedException e) {
					}
					System.out.println("缓存数据清空开始，citySize:" + cityCache.size() + "   hobbySize:" + hobbyCache.size());
					cityCache.clear();
					hobbyCache.clear();
					System.out.println("缓存数据清空完成");
				}
			}
		});
		clearThread.setDaemon(true);
		clearThread.start();
	}

}
